package org.atlantis.juc.actor;

import java.util.LinkedList;
import java.util.Queue;

public abstract class Actor<T> {

	private volatile boolean isExited = false;
	private Queue<T> messageQueue = new LinkedList<T>();
	ActorContext context;

	protected Actor() {
		this.context = new ActorContext();
	}

	protected abstract void receive(T message);

	void execute() {
		T message = null;
		synchronized (messageQueue) {
			message = messageQueue.poll();
		}
		if (message != null) receive(message);
	}

	boolean isExited() {
		return isExited;
	}

	int getMessageCount() {
		return messageQueue.size();
	}

	protected void exit() {
		this.isExited = true;
	}

	public void post(T message) {
		if (isExited) return;
		synchronized (messageQueue) {
			messageQueue.offer(message);
		}
		Dispatcher.getInstance().readyToExecute(this);
	}
}
